import { createRouter, createWebHistory, type RouteRecordRaw } from 'vue-router'

// 基础路由
const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/login',
      name: 'login',
      component: () => import('@/views/login.vue'),
      meta: { detail: '登录页' }
    },
    {
      path: '/',
      name: 'home1',
      redirect: '/home',
      component: () => import('@/views/main.vue'),
      children: []
    },

  ]
})

interface DynamicRoute {
  label: string;
  icon: string;
  path: string
  name: string
  url: string
  meta?: Record<string, any>
  children?: DynamicRoute[]
}

/**
 * 转换后端路由为Vue路由格式
 */ const transformDynamicRoute = (route: DynamicRoute): RouteRecordRaw => {
  // 处理有children的路由
  if (route.children?.length) {
    return {
      path: route.path,
      name: route.name,
      component:
        () => import(`@/views/${route.url}/index.vue`),

      children: route.children.map(child => ({
        ...transformDynamicRoute(child),

      }))
    }
  }

  // 处理普通路由
  return {
    path: route.path,
    name: route.name || route.path.replace('/', ''),
    component: () => import(`@/views/${route.url}/index.vue`)
  }
}

/**
 * 添加动态路由
 */
export const addDynamicRoutes = (dynamicRoutes: DynamicRoute[]) => {
  // 找到index路由
  const homeRoute = router.getRoutes().find(route => route.name === 'home1')
  // 转换并添加子路由
  dynamicRoutes.forEach(route => {
    const transformedRoute = transformDynamicRoute(route)

    // 检查是否已存在相同路径的路由
    const existingRoute = homeRoute?.children?.find(r => r.path === transformedRoute.path)
    if (!existingRoute) {
      router.addRoute('home1', transformedRoute)
    }
  })

  // 更新本地存储
  localStorage.setItem('dynamic_routes', JSON.stringify(dynamicRoutes))
}

export const initDynamicRoutes =  () => {
  const savedRoutes = localStorage.getItem('dynamic_routes')
  if (savedRoutes) {
      const routes = JSON.parse(savedRoutes)
       addDynamicRoutes(routes) // 确保这是异步操作
  }
}

export default router